package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;

import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.system.domain.Contract;
import com.zzyl.system.mapper.ContractMapper;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Optional;

/**
 * checkinService业务层处理
 *
 * @author yuan
 * @date 2025-05-23
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {

    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;


    /**
     * 查询checkin
     *
     * @param id checkin主键
     * @return checkin
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询checkin列表
     *
     * @param checkIn checkin
     * @return checkin
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增checkin
     *
     * @param checkIn checkin
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改checkin
     *
     * @param checkIn checkin
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除checkin
     *
     * @param ids 需要删除的checkin主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除checkin信息
     *
     * @param id checkin主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void apply(CheckInApplyDto dto) {
        //判断是否入住
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elderInDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));
        if (elderInDb != null) {
            if (elderInDb.getStatus() == 1 || elderInDb.getStatus() == 2 || elderInDb.getStatus() == 4) {
                throw new ServiceException("该老人已入住");
            }
        }
        //跟新床位状态
        Long bedId = dto.getCheckInConfigDto().getBedId();
        int count = bedMapper.updateBedStatus(bedId);
        if (count == 0) {
            throw new ServiceException("该床位已入住");
        }
        //新增或更新老人
        Elder elder = addOrUpdateElder(checkInElderDto, bedId, elderInDb);
        //新增签约办理
        addContract(dto, elder);
//新增入住信息
        CheckIn checkIn = addCheckIn(dto, elder);
        //新增入住信息
        addCheckInConfig(dto, checkIn);


    }
//详情
    @Override
    public CheckInDetailVo detail(Long id) {
CheckInDetailVo  vo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = getById(id);
        //查询老人信息
      Optional.ofNullable(elderMapper.selectById(checkIn.getElderId()))
              .ifPresent(e->{
                  CheckInElderVo elderVo  = BeanUtil.toBean(e, CheckInElderVo.class);
                  int age = IdcardUtil.getAgeByIdCard(e.getIdCardNo());
                  elderVo.setAge(age);
                  vo.setCheckInElderVo(elderVo);
              });

        //查询合同
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId,checkIn.getElderId()));
        vo.setContract(contract);
        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);

        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);
        //转换家属列表
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> familyList = JSONUtil.toList(remark, ElderFamilyVo.class);
        vo.setElderFamilyVoList(familyList);


        return vo;
    }

    private void addCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);

    }
    private Elder addOrUpdateElder(CheckInElderDto checkInElderDto, Long elderId, Elder elderInDb) {
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setId(elderId);
        elder.setStatus(1);
        elder.setBedNumber(bedMapper.selectById(elderId).getBedNumber());
        if (elderInDb == null) {
            elderMapper.insert(elder);
            log.info("新增老人{}", elder);
        } else {
            elder.setId(elderInDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }

    private void addContract(CheckInApplyDto dto, Elder elder) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);

        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());

        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate(); // 获取入住结束时间
        contract.setStartDate(DateUtils.toDate(startDate));
        contract.setEndDate(DateUtils.toDate(endDate));
        LocalDateTime now = LocalDateTime.now();
        if (endDate.isBefore(now)) {
            throw new ServiceException("合约结束时间要大于当前时间");
        }
        if (startDate.isBefore(now)) {
            contract.setStatus(1);
        } else {
            contract.setStatus(0);
        }
        //用生成器生成唯一合同编号
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
        log.info("新增合同成功,id={}", contract.getId());
    }

    /**
     * 新增入住信息
     *
     * @param dto
     * @param elder
     * @return
     */
    private CheckIn addCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        save(checkIn);
        log.info("新增入住信息成功,id={}", checkIn.getId());
        return checkIn;
    }
}
